package org.example.edusmart.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.edusmart.pojo.LoginUserPojo;
import org.example.edusmart.utils.JwtUtils;
import org.example.edusmart.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException  {

        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //解析token
        String subject;
        try {
            Claims claims = jwtUtils.parseJwt(token);
            subject = String.valueOf(claims.get("id"));
        } catch (Exception e) {
            filterChain.doFilter(request, response);
            return;
        }

        //从redis中获取用户信息
        String redisKey = "login:" + subject;

        LoginUserPojo loginUser =redisUtils.getObject(redisKey);

        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }

        //SecurityContextHolder
        // loginUser.getAuthorities()权限
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                loginUser, null,loginUser.getAuthorities()
        );
        SecurityContextHolder.getContext().setAuthentication(authentication); //将authentication保存到安全下文

        filterChain.doFilter(request, response); //放行
    }
}
